//
//  BHFunDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/23.
// 趣玩详情

import UIKit

class BHFunDetailViewController: BHBaseViewController {
    
    lazy var bottomView: BHFunDetailBottomView = {
        let view = BHFunDetailBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.height-BHFunDetailBottomView.bottomHeight, width: UIScreen.width, height: BHFunDetailBottomView.bottomHeight)
        view.delegate = self
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-BHFunDetailBottomView.bottomHeight)
        view.delegate = self
        view.dataSource = self
        view.isHidden = true
        return view
    }()
    
    lazy var popView: BHDialogView = {
        let view = BHDialogView.loadFromXib()
        view.delegate = self
        view.pop_traling.constant = 43
        return view
    }()
    
    var funId: String = ""
    fileprivate var funDetailModel = BHFunDetailInfoModel.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "详情"
        self.registerCell()
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomView)
        self.view.addSubview(self.popView)
        self.configRight()
        
        self.loadFunDetailService()
    }
    
    private func configRight() {
        self.bh_navigationBar.rightBtn.isHidden = false
        self.bh_navigationBar.more_btn.isHidden = false
        
        self.bh_navigationBar.rightBtn.setTitle("", for: .normal)
        self.bh_navigationBar.rightBtn.setImage(UIImage.init(named: "bh_com_collect_normal_black"), for: .normal)
        self.bh_navigationBar.rightBtn.setImage(UIImage.init(named: "bh_competitionDetail_collected_sign"), for: .selected)

        
        self.bh_navigationBar.more_btn.setImage(UIImage.init(named: "bh_circle_detail_nav_more"), for: .normal)

    }
    
    override func rightBtnAction() {
        self.collectOrNot()
    }
    
    override func moreBtnAction() {
        self.popView.show()
    }
    
    private func registerCell() {
        self.tableView.regiseterNib(nibName: "BHFunDetailInfoCell")
        self.tableView.regiseterNib(nibName: "BHFunDetailApplyInfoCell")
        self.tableView.regiseterNib(nibName: "BHComAddOrShowImageCell")
        self.tableView.regiseterNib(nibName: "BHFunDetailMoreMarkTextCell")
        self.tableView.regiseterNib(nibName: "BHCompetitionTipTableViewCell")
    }
}

extension BHFunDetailViewController: BHFunDetailBottomViewDelegate {
    func funBottomDidSelectTypeAction(type: Int) {
        if type == 0 {
            if self.funDetailModel.signStatus == 1 {
                let applyVC =  BHFunApplyWriteViewController.init()
                applyVC.funId = self.funId
                applyVC.price = self.funDetailModel.price
                self.navigationController?.pushViewController(applyVC, animated: true)
                applyVC.refreshDetailBlock = { [weak self] in
                    self?.loadFunDetailService()
                }
            }
        }
        if type == 1 { // 群聊
            if self.funDetailModel.groupId.isEmpty == true {
                BHToast.toast(text: "当前赛事群未组建")
                return
            }
            BHRouter.shared.bh_goGroupChat(groupId: self.funDetailModel.groupId)
        }
        if type == 2 { // 打电话
            BHCommonTool.telAct(self.funDetailModel.contactNumber) { (open) in
                if open == false {
                    BHToast.toast(text: "当前设备暂不支持拨打电话")
                }
            }
        }
    }
}

extension BHFunDetailViewController: BHDialogViewDelegate {
    func didDialogSelectIndex(type: Int) {
        if type == 0 { // 分享
            BHToast.toast(text: String.serviceWaiteOpen)
        }
        if type == 1 { // 举报
            BHRouter.shared.bh_report(type: 4, businessId: self.funId)
        }
    }
}

extension BHFunDetailViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 2 {
            if self.funDetailModel.urlList.count != 0 {
                return 1+self.funDetailModel.imageRows
            }
        }
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return BHFunDetailInfoCell.cellHeight
        }
        if indexPath.section == 1 {
            return BHFunDetailApplyInfoCell.cellHeight
        }
        if indexPath.section == 2 {
            if indexPath.row == 0 {
                if self.funDetailModel.introduce.isEmpty == false {
                    return 70+self.funDetailModel.introduceHeight
                }else {
                    return 80
                }
            }else {
                return 120
            }
        }
        if indexPath.section == 3 { // 退款说明
            return 60
        }
        return 0
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section != 0 {
            return 10
        }else {
            return CGFloat.leastNormalMagnitude
        }
    }
    
}

extension BHFunDetailViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section != 0 {
            let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
            view.backgroundColor = .color_f8f8f8
            return view
        }
        
        return nil
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHFunDetailInfoCell", for: indexPath) as! BHFunDetailInfoCell
            cell.model = self.funDetailModel
            return cell
        }else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHFunDetailApplyInfoCell", for: indexPath) as! BHFunDetailApplyInfoCell
            cell.model = self.funDetailModel
            cell.number_label.addViewAction {[weak self] (_) in
                BHRouter.shared.bh_goUserList(type: 2, userId: nil, businessId: self?.funId ?? "")
            }
            cell.publishUser_btn.addBtnAction(action: {[weak self] (_) in
                if self?.funDetailModel.launchUserId != nil {
                    BHRouter.shared.bh_goPersonalHome(userId: self?.funDetailModel.launchUserId ?? "")
                }
            }, for: .touchUpInside)
            
            cell.relationStadiumView.addViewAction {[weak self] (_) in
                if self?.funDetailModel.venueId.isEmpty == false {
                    BHRouter.shared.bh_goStadiumDetail(stadium: self?.funDetailModel.venueId ?? "")
                }
            }
            return cell
        }else if indexPath.section == 2{
            return self.cellForFunRemark(indexPath: indexPath)
        }else {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "BHCompetitionTipTableViewCell", for: indexPath) as! BHCompetitionTipTableViewCell
            cell.backRuleBtn.setTitle(" 报名截止后退出将不退换报名费", for: .normal)
            return cell
        }
    }
    
    func cellForFunRemark(indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell : BHFunDetailMoreMarkTextCell = self.tableView.dequeueReusableCell(withIdentifier: "BHFunDetailMoreMarkTextCell", for: indexPath) as! BHFunDetailMoreMarkTextCell
            if self.funDetailModel.introduce.isEmpty == true {
                cell.text_view.text = "暂无活动描述"

            }else {
                cell.text_view.text = self.funDetailModel.introduce
            }
            cell.text_view.isEditable = false
            cell.text_view.isScrollEnabled = false
            cell.place_label.isHidden = true
            return cell
        }else {
            let cell : BHComAddOrShowImageCell = self.tableView.dequeueReusableCell(withIdentifier: "BHComAddOrShowImageCell", for: indexPath) as! BHComAddOrShowImageCell
            if self.funDetailModel.urlList.count != 0 {
                cell.configImage(imageArray: self.funDetailModel.urlList, index: indexPath.row-1,canAdd: false)
            }
            cell.didImageActBlock = { [weak self] (index, chose,model) in
                if chose == true { // 预览
                    BHMediaTool.showPreview(array: self?.funDetailModel.urlList ?? [], current: index)
                }else { // 添加
                    
                }
            }
            return cell
        }
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
}

extension BHFunDetailViewController {
    func loadFunDetailService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.fun_detail_url, paramters: ["id":self.funId,"latitude":BHLocationManager.shared.latitude,"longitude":BHLocationManager.shared.longitude]) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                let resutl = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let model = BHFunDetailInfoModel.init()
                model.parseDic(resutl)
                self.funDetailModel = model
                self.tableView.isHidden = false
                self.tableView.reloadData()
                self.bottomView.model = model
                
                self.bh_navigationBar.rightBtn.isSelected = model.collectionFlag == 1
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    
    func collectOrNot()  {
        SVProgressHUD.show()
        BHCommonService.collectOrNotService(type: 1, businessId: self.funId) { (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                if self.funDetailModel.collectionFlag == 0 {
                    self.funDetailModel.collectionFlag = 1
                    BHToast.toast(text: "已收藏")
                }else {
                    self.funDetailModel.collectionFlag = 0
                    BHToast.toast(text: "收藏已取消")
                }
                
                self.bh_navigationBar.rightBtn.isSelected = self.funDetailModel.collectionFlag == 1
                
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
